<template>
    <div class="d">
        <h1>注册</h1>
        <div class="imgs">
            <el-upload class="avatar-uploader" :show-file-list="false" :http-request="uploadSectionFile">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </div>
        <el-form ref="form" :label-position="labelPosition" :rules="rules" :model="ruleForm">

            <el-form-item label="用户名" prop="userName">
                <el-input v-model="ruleForm.userName" placeholder="请输入账号"></el-input>
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input show-password v-model="ruleForm.password" placeholder="请输入密码"></el-input>
            </el-form-item>

            <el-form-item label="确认密码" prop="password2">
                <el-input show-password v-model="ruleForm.password2" placeholder="请再次输入密码"></el-input>
            </el-form-item>
            <el-button @click="register(form)" class="g">注册</el-button>
        </el-form>
        <span @click="router.push('/login')">←返回登录</span>
    </div>
</template>

<script setup>
import { ref, reactive } from "vue"
import { useRouter } from "vue-router"
import axios from "../axios/index.js"
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
//头像的路径
const imageUrl = ref(require("../assets/img/mrtx.webp"))
//路由
const router = useRouter()
//form表单的文字方位
let labelPosition = ref("top")
// from表单的三个参数
let ruleForm = reactive({
    userName: "",
    password: "",
    password2: "",
})
//接收from表单的ref属性
let form = ref("")

//正则验证
let validate = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'));
    } else {
        if (ruleForm.password2 !== '') {
            ruleForm.password2 === ""
        }
        callback();
    }
};

let validate2 = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'));
    } else if (value !== ruleForm.password) {
        callback(new Error('两次输入密码不一致！'));
    } else {
        callback();
    }
};

let rules = reactive({
    userName: [
        { required: true, trigger: 'blur', message: '请输入用户名' },
        { message: '长度在2到16个字符', min: 2, max: 16, }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur', },
        { message: '长度在6到16个字符', min: 6, max: 16, trigger: 'blur' },
        { validator: validate, trigger: 'blur' }
    ],
    password2: [
        { required: true, message: '请输入密码', trigger: 'blur', },
        { message: '长度在6到16个字符', min: 6, max: 16, trigger: 'blur' },
        { validator: validate2, trigger: "blur" }
    ]
})

//注册按钮的点击事件
function register(formEl) {
    if (!formEl) return
    formEl.validate(async (valid) => {
        //正则全部验证成功
        if (valid) {
            let { data } = await axios({
                url: "/admin/register",
                method: 'post',
                data: {
                    userName: ruleForm.userName,
                    userPwd: ruleForm.password,
                    userimg: imageUrl.value,
                }
            });
            if (data === "用户注册成功") {
                ElMessage({
                    message: data,
                    type: 'success',
                })
                //注册成功跳转到登录页
                router.push("/login/land")
                formEl.resetFields()
                return
            } else if (data === "用户名重复") {
                ElMessage({
                    message: data,
                    type: 'warning',
                })
                formEl.resetFields()
                return
            }
        } else {
            ElMessage({
                    message: ("请填写完成用户名或用户密码"),
                    type: 'warning',
            })
            return
        }
    })
}

//上传头像
async function uploadSectionFile(res) {
    //res：图片的file对象
    const formData = new FormData()
    formData.append("img", res.file, res.file.name)
    let { data: { data } } = await axios.post("/upload", formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
    });
    if (data) {
        imageUrl.value = `http://localhost:8848${data}`
    }
}
</script>

<style lang="less" scoped>
.d>span {
    color: #9c88ff;
    position: absolute;
    right: 0;
    bottom: .2rem;
    font-size: .12rem;
    cursor: pointer;
}

.avatar-uploader{
    border: .01rem solid gainsboro;
    border-radius: 50%;
    height: 1rem;
    font-size: .4rem;
   display: flex;
   justify-content: center;
   align-items: center;
    color: gainsboro;
}

.login-container {
    font-size: .16rem;

    .el-form-item {
        display: flex !important;
    }

    .el-form--inline {
        display: block !important;
    }

    .login_title {
        text-align: center;
        color: #505458;
    }
}

.d {
    width: 2.5rem;
    height: 5.5rem;
    position: relative;
}

.d h1 {
    margin-top: .2rem;
    font: 900 .3rem '';
}

.f {
    float: right;
    margin: .1rem 0;
    color: #9c88ff;
}

.con {
    margin-top: .6rem;
    display: flex;
    justify-content: space-between;
}

.g {
    color: white !important;
    display: block;
    margin: .2rem auto 0;
    width: 1.2rem;
    height: .6rem;
    border-radius: .3rem;
    border: 0;
    font: 900 .2rem '';
    text-align: center;
    background: linear-gradient(to left, #9c88ff, #3cadeb);
}

.imgs {
    width: 1rem;
    height: 1rem;
    margin: auto;
}

.imgs img {
    width: 1rem;
    height: 1rem;
    border-radius: 100%;
}
</style>